import React, { useRef, useEffect, useState } from 'react';
import { connect } from 'umi';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { useDrag, DndProvider } from 'react-dnd';
import { Button, Dropdown, Menu, Modal, Table, Space, Tag, message } from 'antd';
import styles from './WorkFlowEditor.less';
import MainCanvas from './MainCanvas';
import RightPannel from './rightpannel/RightPannel';
import classNames from 'classnames';
import { EventItemType, NewWorkflowFile } from './dict';
import { CanvasContext } from './CanvasContext';
import { DownOutlined, SettingOutlined, PlusOutlined } from '@ant-design/icons';

function FlowItem(props) {
  const { item } = props;

  const [collected, drag] = useDrag(() => ({
    type: item.type,
    item: { type: item.type },
  }));

  return (
    <div ref={drag} className={styles.flowItem}>
      <i className={classNames('iconfont', item.icon)} style={{ color: item.color }} />
      {item.label}
    </div>
  );
}

function WorkFlowEditor(props) {
  const { wfeditor, dispatch, match } = props;
  const workflowId = match.params.workflowId;
  const appId = match.params.appId;

  // useEffect(() => {
  //   if (activeKey.length) intBpmnJson();
  // }, [activeKey]);

  const intBpmnJson = async (type, currentKey) => {
    // const params = {
    //   entryId: workflowId,
    // };
    // let toActive = activeKey;
    // if (type == 'new') {
    //   toActive = '0';
    // }
    // const res = await api.getListFlowEntryPublish(params.entryId);
    // if (res && res.code == '200') {
    //   let d;
    //   res.data.forEach((elem) => {
    //     if (elem.publishVersion == (currentKey ? currentKey : toActive)) {
    //       d = elem;
    //     }
    //   });
    //   if (!d && res.data.length) {
    //     d = res.data[0];
    //   }
    //   setActiveKey([d.publishVersion]);
    //   dispatch({
    //     type: 'wfeditor/setSelectedFlow',
    //     payload: d,
    //   });
    //   if (d && d.bpmnJson) {
    //     let json = JSON.parse(d.bpmnJson);
    //     dispatch({
    //       type: 'wfeditor/updateGraphCells',
    //       payload: json,
    //     });
    //     if (type !== 'update') {
    //       dispatch({
    //         type: 'wfeditor/selected',
    //         payload: { id: null, type: null },
    //       });
    //       let propList = [];
    //       json.cells.forEach((item) => {
    //         propList.push({
    //           id: item.id,
    //           data: item.data,
    //         });
    //       });
    //       dispatch({
    //         type: 'wfeditor/setPropList',
    //         payload: propList,
    //       });
    //     }
    //   } else {
    //     dispatch({
    //       type: 'wfeditor/updateGraphCells',
    //       payload: NewWorkflowFile(),
    //     });
    //   }
    // }
  };

  const canvasRef = useRef(null);

  const onPrintJson = () => {
    console.log('onPrintJsononPrintJsononPrintJson');
    // if (canvasRef.current && wfeditor.wfContent.entryPublishId) {
    //   const graphJson = canvasRef.current.graphJson();
    //   // console.log('graph json => ', JSON.stringify(graphJson));
    //   console.log('graph json => ', graphJson);
    //   // console.log('graphJson', graphJson.cells[3] ? graphJson.cells[3].data : '');
    //   let params = {
    //     entryId: workflowId,
    //     // categoryId: wfeditor.wfContent.categoryId,
    //     bindFormType: 1,
    //     defaultRouterName: '/test',
    //     detlFlag: true,
    //     bpmnJson: JSON.stringify(graphJson),
    //     entryPublishId: wfeditor.wfContent.entryPublishId,
    //   };
    //   api.updateWorkflowById(params).then((r) => {
    //     if (r.code && r.code == '200') {
    //       // intBpmnJson('update');
    //     }
    //   });
    // }
  };

  // updateGraphProps 用法：
  //   id: 可以是具体id | *， *表示所有cell
  //   propsByPath:
  //      'data':  将 value 的值直接调用 cell.setData();
  //      'data/name': 修改 cell 的标题时需要用这种，同时会修改 cell.data 值
  //      {cell的属性值}: 例如： 'attrs/label/text'，修改 cell 属性值
  return (
    <CanvasContext.Provider
      value={{
        graphCanvasRef: canvasRef,
        updateGraphProps: (id, propsByPath, value) =>
          canvasRef.current.updateGraphProps(id, propsByPath, value),
      }}
    >
      <DndProvider backend={HTML5Backend}>
        <div className={styles.xflowMain}>
          <div className={styles.actionBar}>
            <div className={styles.leftBar}>
              {/* <FlowItem
              item={{
                type: EventItemType.WorkTask,
                label: '流程节点',
                icon: 'icon-liuchengjiedian',
                color: '#007AFFFF',
              }}
              key="worktask"
            />
            <FlowItem
              item={{
                type: EventItemType.VerifyTask,
                label: '审批节点',
                icon: 'icon-shenpijiedian',
                color: '#FF9400FF',
              }}
              key="verifytask"
            />
            <Button style={{ marginLeft: '10px' }} onClick={onPrintJson}>
              PrintJson
            </Button> */}
            </div>
            {wfeditor.selectedType == EventItemType.WorkTask && (
              <div className={styles.rightBar}>流程节点属性</div>
            )}
            {wfeditor.selectedType == EventItemType.VerifyTask && (
              <div className={styles.rightBar}>审批节点属性</div>
            )}
            {wfeditor.selectedType == EventItemType.EndEvent && (
              <div className={styles.rightBar}>连线属性</div>
            )}
          </div>

          <div className={styles.bodyWapper}>
            <div className={styles.canvas}>
              <MainCanvas ref={canvasRef} flowGraphData={wfeditor.graphCells} dispatch={dispatch} />
            </div>

            <div className={styles.pannels}>
              <RightPannel appId={appId} />
            </div>
          </div>
        </div>
      </DndProvider>
    </CanvasContext.Provider>
  );
}

export default connect(({ wfeditor, leftPanel }) => ({ wfeditor, leftStore: leftPanel }))(
  WorkFlowEditor,
);
